<route lang="yaml">
  meta:
    title: 供应商管理
  </route>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

interface Supplier {
  supplierId: number
  supplierName: string
  city: string
  phoneNumber: string
  status: string
  createTime: string
  updateTime: string
}

// 表格数据
const tableData = ref<Supplier[]>([
  {
    supplierId: 1,
    supplierName: '华为科技',
    city: '深圳',
    phoneNumber: '0755-12345678',
    status: '启用',
    createTime: '2024-03-15',
    updateTime: '2024-03-15',
  },
  {
    supplierId: 2,
    supplierName: '小米生态',
    city: '北京',
    phoneNumber: '010-87654321',
    status: '停用',
    createTime: '2024-02-20',
    updateTime: '2024-04-10',
  },
])

// 弹窗控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

// 表单数据
const addFormData = reactive<Omit<Supplier, 'supplierId' | 'createTime' | 'updateTime'>>({
  supplierName: '',
  city: '',
  phoneNumber: '',
  status: '启用',
})

const editFormData = reactive<Supplier>({
  supplierId: 0,
  supplierName: '',
  city: '',
  phoneNumber: '',
  status: '启用',
  createTime: '',
  updateTime: '',
})

// 状态选项
const statusOptions = [
  { value: '启用', label: '启用' },
  { value: '停用', label: '停用' },
]

// 验证规则
const rules = reactive({
  supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  city: [{ required: true, message: '请输入所在城市', trigger: 'blur' }],
  phoneNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^(\d{3,4}-)?\d{7,8}$/, message: '格式示例：0755-12345678', trigger: 'blur' },
  ],
})

// 新增供应商
function handleAdd() {
  addFormRef.value?.resetFields()
  addDialogVisible.value = true
}

// 编辑供应商
function handleEdit(row: Supplier) {
  Object.assign(editFormData, row)
  editDialogVisible.value = true
}

// 删除供应商
async function handleDelete(row: Supplier) {
  try {
    await ElMessageBox.confirm(
      `确定删除供应商【${row.supplierName}】吗？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const index = tableData.value.findIndex(item => item.supplierId === row.supplierId)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }
  catch {
    // 取消删除
  }
}

const searchKeyword = ref<string>('')

// 提交新增
function submitAdd() {
  addFormRef.value?.validate((valid) => {
    if (valid) {
      const newId = tableData.value.length
        ? Math.max(...tableData.value.map(p => p.supplierId)) + 1
        : 1

      tableData.value.push({
        supplierId: newId,
        ...addFormData,
        createTime: new Date().toISOString().split('T')[0],
        updateTime: new Date().toISOString().split('T')[0],
      })
      addDialogVisible.value = false
      ElMessage.success('新增成功')
    }
  })
}

// 提交编辑
function submitEdit() {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      const index = tableData.value.findIndex(item => item.supplierId === editFormData.supplierId)
      if (index > -1) {
        tableData.value.splice(index, 1, {
          ...editFormData,
          updateTime: new Date().toISOString().split('T')[0],
        })
        editDialogVisible.value = false
        ElMessage.success('修改成功')
      }
    }
  })
}
</script>

<template>
  <div>
    <FaPageMain>
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            <span class="ml-1">新增供应商</span>
          </el-button>
        </div>

        <div class="search-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索供应商名称"
            clearable
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table
          :data="tableData.filter(data =>
            !searchKeyword
            || data.supplierName.toLowerCase().includes(searchKeyword.toLowerCase()),
          )"
          style="width: 100%;"
          max-height="calc(100vh - 200px)"
        >
          <el-table-column prop="supplierId" label="供应商ID" width="120" />
          <el-table-column prop="supplierName" label="供应商名称" />
          <el-table-column prop="city" label="所在城市" width="120" />
          <el-table-column prop="phoneNumber" label="联系电话" width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="120" />
          <el-table-column prop="updateTime" label="更新时间" width="120" />
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </FaPageMain>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增供应商"
      width="600px"
    >
      <el-form
        ref="addFormRef"
        :model="addFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="addFormData.supplierName" />
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-input v-model="addFormData.city" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="addFormData.phoneNumber" placeholder="格式：区号-号码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addFormData.status">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitAdd">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑供应商"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="供应商ID">
          <el-input v-model="editFormData.supplierId" disabled />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="editFormData.supplierName" />
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-input v-model="editFormData.city" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="editFormData.phoneNumber" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editFormData.status">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitEdit">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search-wrapper {
  display: flex;
  gap: 12px;
}

.table-wrapper {
  margin-top: 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}
</style>
